/*
 * Copyright (C) 2012  E-dance Studio Harbin Institute of Technology 
 * Project:campusmobile
 * Author: 初楷博
 * Create Date: 2012-6-9下午07:13:47
 */
package hit.edance.campusmobile.chat.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import hit.edance.campusmobile.chat.activity.ActivityChat;
import hit.edance.campusmobile.chat.database.DBChatHistoryHelper;
import hit.edance.campusmobile.chat.service.CampusMobileService;
import hit.edance.campusmobile.chat.util.ConstantUtil;
import hit.edance.campusmobile.chat.util.StringUtil;

import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smackx.OfflineMessageManager;

import android.content.Context;

/**
 * 离线信息管理
 * 
 * @Project campusmobile
 * @Package hit.edance.campusmobile.chat.model
 * @Class OfflineManager
 * @Date 2012-6-9 下午07:13:47
 * @author 初楷博
 * @version 1.0
 * @since 1.0
 */
public class OfflineManager {

	private static OfflineMessageManager offlineManager = new OfflineMessageManager(
			CampusMobileService.connection);
	private static Map<String, ArrayList<Message>> offlineMsgs = new HashMap<String, ArrayList<Message>>();

	public static void getOfflineMessages() {
		try {
			Iterator<Message> it = offlineManager.getMessages();

			System.out.println(offlineManager.supportsFlexibleRetrieval());
			System.out.println("离线消息数量: " + offlineManager.getMessageCount());

			while (it.hasNext()) {
				Message message = it.next();
				System.out
						.println("收到离线消息, Received from 【" + message.getFrom()
								+ "】 message: " + message.getBody());
				String fromUser = message.getFrom().split("/")[0];

				if (offlineMsgs.containsKey(fromUser)) {
					offlineMsgs.get(fromUser).add(message);
				} else {
					ArrayList<Message> temp = new ArrayList<Message>();
					temp.add(message);
					offlineMsgs.put(fromUser, temp);
				}
			}
			offlineManager.deleteMessages();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void handleOfflineMessages(DBChatHistoryHelper db){
		Set<String> keys = offlineMsgs.keySet();  
        Iterator<String> offIt = keys.iterator();
        ChatEntity chatEntity = null;
        while(offIt.hasNext())  
        {  
        	
        	String key = offIt.next();  
        	String nickname = key;
            ArrayList<Message> ms = offlineMsgs.get(key); 
        	if((chatEntity = MyChatManager.getChatEntityByJID(key)) == null){
    			for(User user : FriendsManager.getInstance().getFriends()){
    				if(user.getJabberId().equals(key))
    					nickname = user.getNickname();
    			}
    			chatEntity = MyChatManager.addChatEntity(new ChatEntity(key,nickname));
    			chatEntity.setChat(CampusMobileService.connection.getChatManager().createChat(key, null));
    		}
            
            for (Message message : ms) {  
        		String messagebody = message.getBody();
        		db.insertChatHistoryItem(new ChatItem(ConstantUtil.JID, key, ChatMessage.MESSAGE_FROM, new Date(), messagebody));
        		chatEntity.getChatlist().add(new ChatMessage(ChatMessage.MESSAGE_FROM, messagebody));
				chatEntity.addUnreadMessageCount();
            }  
        }  
		
		
	}
	public static void deleteMessages() {
		try {
			if (offlineManager != null)
				offlineManager.deleteMessages();
		} catch (XMPPException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
